<template>
    <div class="cart-container">
        <h2>历史订单</h2>
        <div v-for="order in orders" :key="order.id" class="cart-item">
            <input type="checkbox" v-model="order.selected" @change="updateTotalPrice" />
            <div class="cart-item-info" @click="viewProduct(order.product)">
                <img :src="order.product.imageUrl" alt="商品图片" class="cart-item-image" />
                <span style="max-width: 80%; margin-left: 20px;">{{ order.product.name }}</span>
                <span style="margin-left: 20px; color: #999;">X &nbsp;{{ order.quantity }}</span>
            </div>
            <span style="color: red;">{{ order.totalPrice | currency }}</span>
        </div>
        <div class="cart-footer">
            <button @click="deleteOrders">删除</button>
        </div>
    </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { get, post } from "../until/request";
import Swal from 'sweetalert2';

const router = useRouter();

const orders = ref([]);  // 历史订单
const userInfo = ref();  // 用户信息
const orderIds = ref([]); // 获取选中订单的ID

onMounted(() => {
    const storedData = localStorage.getItem('login');
    if (storedData) {
        userInfo.value = JSON.parse(storedData);
        try {
            getOrderHistory(); // 获取订单历史信息
        } catch (error) {
            console.error("Error fetching order history data:", error);
        }
    }
});

// 获取订单历史信息
async function getOrderHistory() {
    const response = await get("/user/getHistoryOrder", { userId: userInfo.value.id });
    console.log(response);
    if (response && response.code === 1) {
        orders.value = response.data.map(order => ({
            ...order,
            selected: false // 初始化为未选中
        }));
    }
}

// 删除选中订单
async function deleteOrders() {
    const selectedOrders = orders.value.filter(order => order.selected);
    orderIds.value = selectedOrders.map(order => order.id);  // 获取选中订单的ID

    if (selectedOrders.length === 0) {
        Swal.fire({
            title: '提示',
            text: '请选择至少一个订单进行删除',
            icon: 'warning',
            confirmButtonText: '确定'
        });
        return;
    }

    try {
        const response = await post("/user/deleteHistoryOrder", {
            cartIds: orderIds.value,
            userId: userInfo.value.id
        });
        if (response && response.code === 1) {
            Swal.fire({
                title: '提示',
                text: '订单删除成功',
                icon: 'success',
                confirmButtonText: '确定'
            });
            getOrderHistory(); // 重新获取订单历史信息
        } else {
            Swal.fire({
                title: '提示',
                text: '订单删除失败',
                icon: 'error',
                confirmButtonText: '确定'
            });
        }
    } catch (error) {
        console.error("Error deleting orders:", error);
        Swal.fire({
            title: '错误',
            text: '删除订单时出错',
            icon: 'error',
            confirmButtonText: '确定'
        });
    }
}

// 查看商品详情
function viewProduct(product) {
    // 将产品信息存储到 localStorage
    localStorage.setItem('selectedProduct', JSON.stringify(product));
    router.push({ name: 'ProductDetail' });
}
</script>

<style lang="scss" scoped>
.cart-container {
    padding: 20px;
    background-color: #f9f9f9;
}

.cart-item {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 10px;
    border-bottom: 1px solid #ddd;

    input[type="checkbox"] {
        width: 20px;
        height: 20px;
        margin-right: 30px;
    }

    .cart-item-info {
        width: 100%;
        display: flex;
        align-items: center;
        justify-content: start;

        .cart-item-image {
            width: 100px;
            height: auto;
            object-fit: cover;
        }
    }
}

.cart-footer {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    background-color: #fff;
    padding: 10px;
    box-shadow: 0 -2px 5px rgba(0, 0, 0, 0.1);
    display: flex;
    justify-content: end;
    align-items: center;

    button {
        background-color: #007bff;
        color: white;
        padding: 10px 20px;
        border: none;
        border-radius: 4px;
        cursor: pointer;
    }

    button:hover {
        background-color: #0056b3;
    }
}
</style>